package crm8000.services

import org.springframework.web.context.request.RequestContextHolder;

import crm8000.Models.Org;
import crm8000.Models.User;
import crm8000.helper.PinYinHelper
import crm8000.helper.Result
import grails.transaction.Transactional

@Transactional
class UserService {
	BizLogService bizLogService

	def doLogin(String loginName, String password) {
		def user = User.findByLoginNameAndPassword(loginName, password.encodeAsMD5())

		if (user) {
			if (!user.enabled) {
				return new Result(success: false, msg: "当前用户已经被禁止登录")
			}

			this.session.loginUserId = user.id
			this.session.loginUserName = user.name

			bizLogService.log("登录系统")

			return new Result(success: true)
		} else {
			return new Result(success: false, msg: "用户名或者密码错误")
		}
	}

	def getSession(){
		RequestContextHolder.currentRequestAttributes().getSession()
	}

	def getLoginUserName() {
		return this.session.loginUserName
	}

	def getLoginUserId() {
		return this.session.loginUserId
	}
	
	def getLoginUser() {
		return User.get(this.loginUserId)
	}

	def clearLoginUserInSession() {
		this.session.loginUserId = null
		this.session.loginUserName = null
	}

	def changeMyPassword(String userId, String oldPassword, String newPassword) {
		if (this.loginUserId != userId) {
			return new Result(success: false, msg: "当前用户Session失效，请重新登录系统")
		}

		def user = User.findByIdAndPassword(userId, oldPassword.encodeAsMD5())

		if (!user) {
			return new Result(success: false, msg: "旧密码错误")
		}

		user.password = newPassword.encodeAsMD5()
		user.save()

		return new Result(success: true)
	}

	Result changePassword(String userId, String newPassword) {
		def user = User.findById(userId)
		if (!user) {
			return new Result(success: false, msg: '用户不存在')
		}

		user.password = newPassword.encodeAsMD5()
		user.save()

		return new Result(success: true)
	}

	def allOrgs() {
		def result = []

		// 目前组织结构最大只能为3级
		def orgList1 = Org.findAllByParentId(null, [sort: 'orgCode'])

		for (org1 in orgList1) {
			result.add(org1)
			def orgList2 = Org.findAllByParentId(org1.id, [sort: 'orgCode'])
			org1.leaf = orgList2.size() == 0
			for (org2 in orgList2) {
				org1.children.add(org2)
				def orgList3 = Org.findAllByParentId(org2.id, [sort: 'orgCode'])
				org2.leaf = orgList3.size() == 0

				for (org3 in orgList3) {
					org2.children.add(org3)
					org3.leaf = true
				}
			}
		}

		return result
	}

	def allUsers(orgId) {
		return User.findAllByOrg(Org.get(orgId), [sort: 'orgCode'])
	}

	def orgInfo(id) {
		def org = Org.get(id)
		def parentOrg = Org.get(org.parentId)
		if (parentOrg) {
			org.parentOrgName = parentOrg.name
		}
		return org
	}

	Result editOrg(params) {
		if (params.id) {
			// 编辑
			if (params.parentId == params.id) {
				return new Result(success: false, msg: "上级组织不能是自身")
			}
			def org = Org.get(params.id)
			if (!org) {
				return new Result(success: false, msg: "组织机构不存在，无法编辑")
			}
			
			Boolean parentIdIsChild = false
			def t = Org.get(params.parentId)
			while (t) {
				if (t.id == params.id) {
					parentIdIsChild = true
				}
				
				t = Org.get(t.parentId)
			}
			if (parentIdIsChild) {
				return new Result(success: false, msg: "不能选择下级组织作为上级组织")
			}
			
			def newParentOrg = Org.get(params.parentId)
			org.name = params.name
			org.orgCode = params.orgCode
			org.parentId = params.parentId
			if (newParentOrg) {
				org.fullName = newParentOrg.fullName + "\\" + org.name
			} else {
				org.fullName = org.name
			}
			org.save()
			
			return new Result(success: true)
		} else {
			// 新建
			def org = new Org(name: params.name, orgCode: params.orgCode, parentId: params.parentId)
			def parentOrg = Org.get(params.parentId)
			if (!parentOrg) {
				org.fullName = org.name
			} else {
				org.fullName = parentOrg.fullName + "\\" + org.name
			}
			org.save()
			return new Result(success: true)
		}
	}
	
	Result deleteOrg(String id) {
		def org = Org.get(id)
		if (!org) {
			return new Result(success: false, msg: "组织机构不存在")
		}
		
		def c = User.countByOrg(org)
		if (c > 0) {
			return new Result(success: false, msg: "组织机构[${org.fullName}]下还有人员，不能删除")
		}
		
		c = Org.countByParentId(org.id)
		if (c > 0) {
			return new Result(success: false, msg: "组织机构[${org.fullName}]下还有下级组织，不能删除")
		}
		
		org.delete()
		return new Result(success: true)
	}

	Result editUser(params) {
		if (params.id) {
			// 编辑
			// 检查loginName是否已经被使用
			def c = User.countByLoginNameAndIdNotEqual(params.loginName, params.id)
			if (c > 0) {
				return new Result(success: false, msg: "登录名[${params.loginName}] 已经存在")
			}

			def user = User.get(params.id)
			if (!user) {
				return new Result(success: false, msg: "用户不存在，不能编辑")
			}

			user.loginName = params.loginName
			user.name = params.name
			user.orgCode = params.orgCode
			user.org = Org.get(params.orgId)
			user.enabled = params.enabled.toBoolean()
			user.save()
			return new Result(success: true, id: user.id)
		} else {
			// 新建
			// 检查LoginName是否已经存在
			def c = User.countByLoginName(params.loginName)
			if (c > 0) {
				return new Result(success: false, msg: "登录名[${params.loginName}] 已经存在")
			}
			def user = new User()
			user.loginName = params.loginName
			user.name = params.name
			user.orgCode = params.orgCode
			user.org = Org.get(params.orgId)
			user.enabled = params.enabled.toBoolean()
			// 新用户用户登录的默认密码为123456
			user.password = "123456".encodeAsMD5()
			user.save()
			return new Result(success: true, id: user.id)
		}
	}

	Result deleteUser(String id) {
		def user = User.get(id)
		if (user.loginName == "admin") {
			return new Result(success:false, msg: "用户admin不能删除")
		}

		// TODO 需要判断用户是否能删除
		user.delete()

		return new Result(success: true)
	}
	
	def queryData(String queryKey) {
		if (!queryKey) {
			return []
		}
		def result = []
		
		queryKey = queryKey.toUpperCase()
		
		def all = User.listOrderByLoginName()
		all.each {
			def added = false;
			def pyList = new PinYinHelper().toPinYin(it.name)
			pyList.each { py ->
				if (py.toUpperCase().startsWith(queryKey)) {
					added = true
					result.add(it)
				}
			}
			
			if (!added) {
				if (it.loginName.toUpperCase().startsWith(queryKey)) {
					result.add(it)
				}
			}
		}
		
		return result
	}
}
